<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="下单平台：" prop="platform">
            <el-select v-model="form.platform" multiple placeholder="请选择下单平台" clearable>
              <el-option v-for="(item, index) in platformList" :key="index" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租机类型：" prop="type">
            <el-select v-model="form.type" placeholder="请选择租机类型" multiple clearable>
              <el-option v-for="(item, index) in rentMobileOrderType" :key="index" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择时间：" prop="start_time">
            <el-date-picker v-model="queryDate" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="开始时间" @change="changeQueryDate" end-placeholder="结束时间"> </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="选择客服：" prop="master_id_list">
        <el-transfer v-model="form.master_id_list" :titles="['未选中', '已选中']" filterable :data="customerList"></el-transfer>
      </el-form-item>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IDictData } from "@/types/dict";
import type { ICustomerScheduleDTO, IMasterCustomer, IMasterCustomerVO, ISearchMasterCustomer } from "@/types/customerSchedule/customerSchedule";
import { commonScheduleInfo } from "@/utils/api/admin/customerSchedule";
import { getCustomerList } from "@/utils/api/admin/user/master";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  platformList: Array<IDictData>;
  rentMobileOrderType: Array<IDictData>;
}
const { platformList, rentMobileOrderType } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const queryDate = defineModel<Array<string>>("queryDate", { required: true });
const form = defineModel<ICustomerScheduleDTO>("form", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
  handleEntityRefresh: [];
}>();

const isDisabledbtn = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");

const customerSearchInfo = ref<ISearchMasterCustomer>({
  size: 200,
  current: 1
});
const customerList = ref<IMasterCustomerVO[]>([]);

const rules = reactive({
  platform: [{ required: true, message: "请选择下单平台", trigger: "blur" }],
  start_time: [{ required: true, message: "请选择日期时间", trigger: "blur" }],
  end_time: [{ required: true, message: "请选择日期时间", trigger: "blur" }],
  master_id_list: [{ required: true, message: "请选择客服", trigger: "blur" }]
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/* 查询 创建时间更改事件 */
function changeQueryDate(data: number[]) {
  if (data !== null) {
    form.value.start_time = data[0] * 1000;
    form.value.end_time = data[1] * 1000;
  } else {
    form.value.start_time = "";
    form.value.end_time = "";
  }
}

/* 获取客服列表 。下次优化，不用这个接口，需要通过用户标签为客服来获取所有客服信息*/
function handleGetCustomerList() {
  getCustomerList<IMasterCustomer, ISearchMasterCustomer>(customerSearchInfo.value).then(res => {
    customerList.value = res.result.data.map(item => {
      return {
        key: item.id,
        label: item.nick_name
      };
    });
    console.log(customerList.value);
  });
}
/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;
  form.value.end_time = "";
  queryDate.value = [];

  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonScheduleInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}
handleGetCustomerList();
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
